import FacebookApi from "./FacebookApi";
import AdInstance = FBInstant.AdInstance;

export const MAIN_ADS_ID: string = "260802084691901_265622730876503";
export const EXCHANGE_COINS_ID: string = "260802084691901_265569684215141";
export const REVIVE_COINS_ID: string = "260802084691901_265603990878377";

export default class FBVideoAdsProvider {

    public static get(id: string) {
        if (this.caches[id] == null) {
            this.caches[id] = new FBVideoAdsProvider(id);
        }
        return this.caches[id];
    }

    private static caches: { [key: string]: FBVideoAdsProvider; } = {};

    private id: string = null;
    private preloadedRewardedVideo: AdInstance = null;
    private needShowNow: boolean = false;

    private callback: Function = null;

    constructor(id: string) {
        this.id = id;
    }

    public init() {
        this.preloadAds();
    }

    public async preloadAds() {
        if (FacebookApi.isFbInstant()) {

            if (this.preloadedRewardedVideo != null) {
                return;
            }

            await FBInstant.getRewardedVideoAsync(
                this.id, // Your Ad Placement Id
            ).then((rewarded) => {
                // Load the Ad asynchronously
                this.preloadedRewardedVideo = rewarded;
                return this.preloadedRewardedVideo.loadAsync();
            }).then(() => {
                cc.log("Rewarded video preloaded");
                if (this.needShowNow) {
                    this._showReal();
                }
            }).catch(function(err) {
                console.error(`Rewarded video failed to preload: ${err.message}`);
            });
        } else {
            return Promise.resolve();
        }
    }

    public show(callback: Function) {
        this.callback = callback;
        if (this.preloadedRewardedVideo) {
            this._showReal();
        } else {
            this.needShowNow = true;
        }
    }

    private _showReal() {
        this.needShowNow = false;
        this.preloadedRewardedVideo.showAsync().then(() => {
            cc.log("Rewarded video watched successfully.");
            this.preloadedRewardedVideo = null;

            if (this.callback) {
                this.callback(true);
            }
            this.preloadAds();
        }).catch((e) => {
            console.error(e.message);

            if (this.callback) {
                this.callback(false);
            }
        });
    }
}
